package graphics.engine;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.media.opengl.GL;

import settings.Settings;


import com.sun.opengl.util.texture.TextureData;
import com.sun.opengl.util.texture.TextureIO;


public class TextureManager 
{
	private Hashtable<String, Integer> textures;
	
	public TextureManager()
	{
		this.textures = new Hashtable<String, Integer>();
	}
	public void add(GL gl, String key) throws IOException
	{
		if(!textures.containsKey(key))
		{
			int[] textureId = new int[1]; 
			gl.glGenTextures(1, textureId, 0);
			gl.glBindTexture(GL.GL_TEXTURE_2D, textureId[0]);
			InputStream stream = new FileInputStream(Settings.ImagePath + key);
			String extension = "";
			if(key.contains(".png"))
			{
				extension = TextureIO.PNG;
			}
			else if (key.contains(".jpg"))
			{
				extension = TextureIO.JPG;
			}

			TextureData data = TextureIO.newTextureData(stream, true, extension);
			gl.glTexImage2D (GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, data.getWidth(), data.getHeight(), 0, GL.GL_RGBA, data.getPixelType(),data.getBuffer());	
			gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
			gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
			gl.glBindTexture(GL.GL_TEXTURE_2D, 0);
			textures.put(key, textureId[0]);
		}
	}
	
	public Integer get(String key)
	{
		return textures.get(key);
	}
}
